<?php
/*
Module: RadLib_SCRIPT.php
Description: RadTemplate library to Templated PHP and Expressions.
*/

use com\org\web\tpl\utils\String as String;
use com\org\web\tpl\TplEngine as TplEngine;

// Library Class Definition
class SCRIPT {
	public function tag_INCLUDE($node) {
		if (!$node->hasParam("uri", "uri"))
			return;
		$uri = $param = $node->getParam("uri");
		$template = $node->getParam("template");
		$template = String::evalBool($template);
		$deref = strcasecmp(substr($param, 0, 1 ), "$" ) === 0;
		if($deref) {
			$param = substr($param, 1);
			try {
				$uri = $node->evalParamRef($param, FALSE);
			}
			catch(\Exception $e) {}
		}

		if (!isset($uri) ) {
			$node->appendTagError("InvalidPageReference: " . $node->getParam("page"));
			return;
		}

		$eng = $node->getEngine();
		$node->push();
		if ($template === TRUE) {
			try {
				$tplEng = new TplEngine();
				$tplEng->setHandlers($eng->getHandlers());
				$params = $node->getParams(array("uri", "template"));
				if (is_array($params) && count($params) > 0) {
					foreach($params as $key => $value) {
						if (String::startsWith($value, "@"))
							$params[$key] = $node->evalParamRef(trim($value, "@"), FALSE);
					}

					$tplEng->setValues($params);
				}

				$content = $tplEng->parse($uri);
				$eng->setContent($content);
			}
			catch(\Exception $e) {
			   $node->appendTagError($e->getMessage());
			}
		}
		else {
			ob_start();
			try {
				include($uri);
				$eng->setContent(ob_get_contents());
			}
			catch (\Exception $e) {
				$node->appendTagError($e);
			}
			ob_end_clean();
		}
		$node->pop();
	}

	public function tag_EVAL($node) {
		$eng = $node->getEngine();
		$node->push();
		$node->evalNodes();
		$code = $eng->getContent();
		$eng->setContent("");
		ob_start();
		$result = eval($code);
		$eng->setContent(ob_get_contents());
		ob_end_clean();
		$node->pop();
	}

	public function __construct($plugin) {
		$plugin->setTagHandlerFunc("eval", "tag_EVAL", $this);
		$plugin->setTagHandlerFunc("include", "tag_INCLUDE", $this);
	}
}
?>